<?php

use Doraemon\tools\Log;

abstract class CallBackActionPlugin extends Yaf_Action_Abstract
{

    const CODE_SUCCESS = 1;

    abstract public function main();

    public function execute()
    {
        try {


            if (static::class == 'TrackingMoreCallBackAction'){
                $callbackResponse = json_decode(file_get_contents("php://input"),true);
            } else {
                $callbackResponse = $this->getRequest()->getPost();
            }

            Log::callback_debug_debug(static::class, [
                "uri" => $this->getRequest()->getRequestUri(),
                "params" => $callbackResponse,
            ]);
            $this->checkModules();
            $this->main();
        } catch (\Exception $e) {
            Log::callback_error_debug(static::class, [
                "uri" => $this->getRequest()->getRequestUri(),
                "params" => $this->getRequest()->getPost(),
                "error" => $e
            ]);
            $this->setError($e->getCode(), $e->getMessage(), $e->getLine());
        }
    }

    protected function checkModules()
    {
        if (isset($_SERVER['APP_MODULES'])) {
            $authorizedModules = explode(",", $_SERVER['APP_MODULES']);
            if (!in_array($this->getModuleName(), $authorizedModules)) {
                throw new \Exception("当前域名不能请求当前模块");
            }
        }
    }

    protected function setSuccessWithText($text)
    {
        $this->getResponse()->setBody($text);
    }

    protected function setSuccess($data = NULL)
    {
        $this->getResponse()->setBody(json_encode([
            "code" => self::CODE_SUCCESS,
            "data" => $data
        ], JSON_UNESCAPED_UNICODE));
    }

    protected function setError($code, $message, $line)
    {
        $this->getResponse()->setBody(json_encode([
            "code" => $line,
            "msg" => $message
        ], JSON_UNESCAPED_UNICODE));
    }
}
